local upload = require "resty.upload"
local cjson = require "cjson"
local http2tcp = require "http2tcp"

local chunk_size = 4096
local form = upload:new(chunk_size)
local file_name = ""
local body = ""
local file 

local function my_get_file_name(res)
    local str = cjson.encode(res)
    -- filename=\"add.c\""
    local filename = string.match(str,'filename=\\\"(.+)\\\"\",')
    return filename
end

while true do
    local typ, res, err = form:read()    
    if not typ then         
	 ngx.print('{"success":false, "msg":"'..tostring(err)..'", "data":{}}')
         return
    end
    
    if typ == "header" then
        if res[1] ~= "Content-Type" then
            file_name = my_get_file_name(res)
            if not file_name then
                ngx.say('{"success":false, "msg":"can not get file name}')
                return
            end
        end
    elseif typ == "body" then
        body = body .. res
    elseif typ == "eof" then
        break
    else
    end
end

local resp = {
	msg = "ok",
	code = 0 
}

local taskid = 1568
local cmd    = "upload"

http2tcp:new("127.0.0.1", 9877)
http2tcp:send({taskid=taskid, is_force=0, name=file_name, command=cmd, payload=body})

local data = http2tcp:receive()
resp.data = data
ngx.say(cjson.encode(resp))

